package com.woniuxueyuan.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.woniuxueyuan.entity.KillOrder;
import com.woniuxueyuan.entity.Order;
import com.woniuxueyuan.mapper.OrderMapper;
import com.woniuxueyuan.util.RabbitmqConst;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 消费者重复消费问题？
 * 产生的原因：消费者正常消费完消息，通过AMQP协议给队列应答，消费者应答出去了
 *                  但是应该网络原因没有收到，导致消费者重复消费
 *
 * 解决方案：1：在发送消息时，取消息中的唯一属性值，存入redis
 *         2：在消费者消费消息前，取尝试是否成功删除唯一属性值（redis  ）
 *
 */

@Component
public class AddKillOrderConsumer {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private OrderMapper orderMapper;
    @RabbitListener(queues = RabbitmqConst.ADDKILLORDER_QUEUE)
    public void receive(String msg, Channel channel, Message message) {
        try {
             //把json字符串转成对象
            KillOrder killOrder = JSON.parseObject(msg, KillOrder.class);
            //如果传过来是数组。第二个参数是泛型的class
//            List<KillOrder> killOrders = JSON.parseArray(msg, KillOrder.class);
            //调mapper
            Boolean delfalg = redisTemplate.delete(killOrder.getKillOrderNum());
            if(delfalg){
                orderMapper.addKillOrder(killOrder);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();

        try {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
}
